package com.tool.util;

import com.tool.bean.TableGenInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringBufferInputStream;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class DaoMappingUtil
{
  private static transient Log log = LogFactory.getLog(DaoMappingUtil.class);

  private static final EntityResolver entityResolver = new EntityResolver()
  {
    public InputSource resolveEntity(String publicId, String systemId)
      throws SAXException, IOException
    {
      InputSource is = new InputSource(new StringBufferInputStream(""));
      is.setPublicId(publicId);
      is.setSystemId(systemId);
      return is;
    }
  };

  public static void addMapping(TableGenInfo info)
  {
    String beanId = StringUtil.getCamel(info.getTableName()) + "DAO";
    String parent = info.getDsName() + "BaseDAO";
    String value = info.getPackageName() + ".dao." + StringUtil.getBeanName(info.getTableName()) + "DAO";
    String mapPath = ConfigUtil.getProperty("dao.file");
    SAXReader reader = new SAXReader();
    reader.setEntityResolver(entityResolver);
    try
    {
      Document doc = reader.read(new File(mapPath));
      List list = doc.selectNodes("beans/bean[@id='" + beanId + "']");
      if ((list != null) && (list.size() > 0))
      {
        if (log.isDebugEnabled())
        {
          log.debug("------------------------------------");
          log.debug("DAO映射文件存在相应的Bean:" + beanId + ",取消添加");
          log.debug("------------------------------------");
        }
        return;
      }
      if (log.isDebugEnabled())
      {
        log.debug("------------------------------------");
        log.debug("DAO映射文件不存在相应的Bean:" + beanId + ",开始添加");
        log.debug("------------------------------------");
      }
      long startTime = System.currentTimeMillis();

      Element elem = (Element)doc.selectSingleNode("beans");
      Element e = elem.addElement("bean");
      e.addAttribute("id", beanId);
      e.addAttribute("parent", parent);
      Element e1 = e.addElement("property");
      e1.addAttribute("name", "mapperInterface");
      e1.addAttribute("value", value);
      XMLWriter writer = new XMLWriter(new FileOutputStream(mapPath), OutputFormat.createPrettyPrint());
      writer.write(doc);
      writer.close();
      long endTime = System.currentTimeMillis();
      if (log.isDebugEnabled())
      {
        log.debug("------------------------------------");
        log.debug("添加结束,耗时:" + (endTime - startTime) + "毫秒");
        log.debug("------------------------------------");
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}